package Controller

import (
	"encoding/json"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/gin-gonic/gin"
	"log"
	"mbti/Global"
	"mbti/model"
	"mbti/response"
	"net/http"
)

func Info(context *gin.Context) {
	student, _ := context.Get("user")
	context.JSON(http.StatusOK, gin.H{
		"code": 200, //状态响应码
		"data": gin.H{ //一个json格式
			"user": student, //键-值
		},
	})
}

func StudentLogin(context *gin.Context) {
	fmt.Println("进入studentlogin")
	// 使用map获取请求的参数
	//var requestMap = make(map[string]string)
	//json.NewDecoder(context.Request.Body).Decode(&requestMap)
	// 使用结构体来请求参数
	var requestStudent = model.Students{}
	json.NewDecoder(context.Request.Body).Decode(&requestStudent) //法一
	//context.Bind(&requestStudent)//法二
	fmt.Println("获取到的数据：", requestStudent.SID, requestStudent.S_PASSWORD)
	Global.Sno = requestStudent.SID

	// 获取参数
	sno := requestStudent.SID
	spassword := requestStudent.S_PASSWORD
	// 数据验证
	//if len(sno) < 2 {
	//	context.JSON(http.StatusUnprocessableEntity, gin.H{"code":422, "msg":"学号必须大于2位！"})
	//	return
	//}

	if len(sno) < 1 {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "学号不能为空",
		})
		return
	}

	if len(spassword) < 6 {
		fmt.Println("密码不能少于6位！", len(spassword))
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码不能少于6位",
		})
		return
	}

	// 学号是否存在
	var student model.Students

	Global.Db.Where("s_id=?", sno).First(&student)
	//fmt.Println("用户名：", student.SID)
	//fmt.Println("用户名：", requestStudent.SID)
	//if student.SID != sno {
	if student.SID != sno {
		//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":422, "msg":"用户不存在！！"})
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "用户不存在",
		})
		return
	}
	////判断密码是否正确
	//fmt.Println(student.S_PASSWORD)
	//fmt.Println(spassword)
	if student.S_PASSWORD != spassword {

		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码错误",
		})
		return
	}
	// 发放tokend
	token, err := Global.ReaeaseTokec(student)
	if err != nil {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "token发放失败?",
		})
		log.Printf("token generate error:%v\n", err)
		return
	}
	// 返回结果
	//context.JSON(200, gin.H{
	//	"code":200,
	//	"data":gin.H{"token":token},
	//	"msg":"登陆成功！",
	//})

	response.Success(context, gin.H{"token": token}, "登陆成功")
}

func StuRegister(context *gin.Context) {
	fmt.Println("进入注册环节啦")
	var requestStudent = model.Students{}
	//var requestClass = model.Classes{}
	json.NewDecoder(context.Request.Body).Decode(&requestStudent)
	sid := requestStudent.SID
	sname := requestStudent.SNAME
	ssex := requestStudent.SSEX
	PassWord := requestStudent.S_PASSWORD
	grade := requestStudent.GRADE
	major_name := requestStudent.MAJOR_NAME
	college_name := requestStudent.COLLEGE_NAME
	class_name := requestStudent.CLASS_NAME

	//fmt.Println("进行注册验证")
	fmt.Println("注册信息", requestStudent.SID, class_name, sname, ssex, PassWord, major_name, college_name, grade)
	Global.Sno = requestStudent.SID
	//Global.Sname = requestStudent.SNAME
	//fmt.Println(Global.Sname)
	//Global.Sname = requestStudent.SNAME

	if len(sid) < 1 {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "学号不能为空",
		})
		return
	}

	if len(PassWord) < 6 {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码不能小于六位",
		})
		return
	}

	if len(sname) < 1 {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "姓名不能为空",
		})
		return
	}

	// 学号是否存在
	var student model.Students

	Global.Db.Where("s_id=?", sid).First(&student)
	//fmt.Println("用户名：", student.SID)
	//fmt.Println("用户名：", requestStudent.SID)
	//if student.SID != sno {
	if student.SID == sid {
		//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":422, "msg":"用户不存在！！"})
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "用户已注册",
		})
		return
	}

	//使用redis来注册用户信息

	fmt.Println("flag", Global.Flag)
	if Global.Flag == true {
		_, err := Global.CDb.Do("SET", sid, PassWord)
		if err != nil {
			fmt.Println(err)
		}

		e, erro := redis.String(Global.CDb.Do("get", sid))
		if erro != nil {
			fmt.Println(erro)
		}
		fmt.Println("看看读到了什么", e)
	}

	newstudent := model.Students{
		SID:          sid,
		SNAME:        sname,
		SSEX:         ssex,
		S_PASSWORD:   PassWord,
		GRADE:        grade,
		MAJOR_NAME:   major_name,
		COLLEGE_NAME: college_name,
		CLASS_NAME:   class_name,
		STYPE:        "1",
	}
	Global.Db.Create(&newstudent)

	token, err := Global.ReaeaseTokec(newstudent)
	if err != nil {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "系统异常",
		})
		log.Printf("token generate error:%v\n", err)
		return
	}

	response.Success(context, gin.H{"token": token}, "注册成功")

}

func StudentLogout(context *gin.Context) {
	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "登出成功",
	})
}

func ChangePassword(context *gin.Context) {
	var id, password, checkPass, currentPass string
	requestStudent := make(map[string]interface{})
	err := context.ShouldBind(&requestStudent)
	id = requestStudent["id"].(string)
	password = requestStudent["password"].(string)
	checkPass = requestStudent["checkPass"].(string)
	currentPass = requestStudent["currentPass"].(string)
	//json.NewDecoder(context.Request.pa).Decode(&requestStudent)
	//err := context.ShouldBind(&requestStudent)
	//if err != nil {
	//	return
	//}
	fmt.Println("修改密码的学生：", id, password, checkPass, currentPass)
	var student model.Students
	err = Global.Db.Where("s_id = ?", id).First(&student).Error
	if err != nil {
		fmt.Println("查询出错")
		return
	}
	if student.S_PASSWORD != currentPass {
		fmt.Println("密码错误")
		context.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	errr := Global.Db.Model(&student).Where("s_id = ?", id).Update("s_password", password).Error
	if errr != nil {
		fmt.Println("修改密码出错")
		return
	}
	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "修改密码成功",
	})
}

// ShowStudent 显示全部学生信息
func ShowStudent(context *gin.Context) {
	var student []model.Students
	Global.Db.Find(&student)
	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "生成学生信息成功",
		"data": student,
	})
}

func EditStudent(context *gin.Context) {
	var request = model.Students{}
	json.NewDecoder(context.Request.Body).Decode(&request)
	fmt.Println("即将更改以下学号的学生", request.SID)
	err := Global.Db.Where("s_id = ?", request.SID).Updates(request).Error
	if err != nil {
		context.JSON(200, gin.H{
			"code": 400,
			"msg":  "修改失败",
		})
		return
	}
	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "更新成功",
	})
}

func DelStudent(context *gin.Context) {
	var request = model.Students{}
	json.NewDecoder(context.Request.Body).Decode(&request)
	fmt.Println("要删除的学生学号", request.SID)
	err := Global.Db.Where("s_id = ?", request.SID).Delete(request).Error
	if err != nil {
		context.JSON(200, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}
	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func StuResult(context *gin.Context) {
	var result []model.Test_results
	Global.Db.Where("s_id = ?", Global.Sno).Find(&result)
	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "生成考试记录成功",
		"data": result,
	})
}

func StuDelResult(context *gin.Context) {
	var request = model.Test_results{}
	json.NewDecoder(context.Request.Body).Decode(&request)
	fmt.Println("要删除的result时间", request.TEST_TIME)
	err := Global.Db.Where("test_time = ?", request.TEST_TIME).Delete(request).Error
	if err != nil {
		context.JSON(200, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}
	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
